﻿#region "Copyright (C) Lenny Granovsky. 2011-2013"
//    This library provides extended cache capabilities to the ASP.NET applications.
//
//                Copyright (C) Lenny Granovsky. 2011-2013. 
//
//    This program is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 2 of the License, or
//    (at your option) any later version.
//
//    This program is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
//    This program comes with ABSOLUTELY NO WARRANTY.
//    This is free software, and you are welcome to redistribute it
//    under certain conditions;
#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MongoDB;
using System.Diagnostics;
using System.Threading;

namespace FlexiCache
{
    /// <summary>
    /// Class provides functionality for Session on Demand. It implements the ISessionOnDemandController interface. 
    /// It uses the MongoDBCacheProviderBase as an underlying storage connector. 
    /// </summary>
    /// <remarks>This class is not intended to be used directly. It used internally by ASP.NET infrastructure.</remarks>
    public class SessionOnDemandProvider : ExternalCacheProviderBase
	{
        public bool IsEnabled { get; set; }

        /// <summary>
        /// Gets or sets the ASP.NET Session ID for current session.
        /// </summary>
        public string AspNetSessionId { get; set; }
        /// <summary>
        /// Gets or sets the ASP.NET Application ID that ASP.NET runtime uses to identify unique application when out-of-proc session is used.
        /// </summary>
        public string AspNetAppId { get; set; }
        /// <summary>
        /// Gets or sets the unique Session Id used to store session data.
        /// </summary>
        protected string SessionId
        {
            get
            {
                return string.Format("{0}{1}", this.AspNetAppId, this.AspNetSessionId);
            }
        }
        /// <summary>
        /// Gets or sets the session timeout.
        /// </summary>
        public int SessionTimeout { get; set; }

        protected string BuildUniqueKey(string key)
        {
            return string.Format("{0}{1}-{2}", this.AspNetAppId, this.AspNetSessionId, key);
        }

        /// <summary>
        /// Default constructor.
        /// </summary>
        public SessionOnDemandProvider()
            : base(CachingConfiguration.Current.SessionOnDemandConfig)
        {
        }

        /// <summary>
        /// Method updates the expiration date and time for specified item to renew it for next session timeout interval.
        /// </summary>
        public void Renew()
        {
            if (this.IsEnabled)
            {
                DateTime utcExpiry = DateTime.UtcNow.AddMinutes(this.SessionTimeout);
                this.CacheStorageAdapter.Renew(this.SessionId, utcExpiry);
            }
        }

        /// <summary>
        /// Method removes all items associated with this session.
        /// </summary>
        public void Clear()
        {
            if (this.IsEnabled)
            {
                this.CacheStorageAdapter.Clear(this.SessionId);
            }
        }

        /// <summary>
        /// Method returns the list of items in the collection for this session.
        /// </summary>
        /// <remarks>This method is resource intensive and is designed for use by customer support. 
        /// Do not use from the application code.</remarks>
        /// <param name="includeActualData">Boolean value indicating where or not the actual data should be included or cleared.</param>
        /// <returns>Returns the list of items in the collection for this session.</returns>
        public List<CacheItemInfo> RetrieveCollection(bool includeActualData)
        {
            if (this.IsEnabled)
            {
                return this.CacheStorageAdapter.RetrieveCollection(this.SessionId, includeActualData);
            }
            return new List<CacheItemInfo>();
        }

        /// <summary>
        /// Method adds data into the session with specified key.
        /// </summary>
        /// <param name="key">Data key.</param>
        /// <param name="entry">Data to cache.</param>
        public void Add(string key, object entry)
        {
            this.Set(key, entry);
        }

        /// <summary>
        /// Method gets a data from the cache using specified key.
        /// </summary>
        /// <param name="key">Data key.</param>
        /// <returns>Returns cached object.</returns>
        public override object Get(string key)
        {
            key = BuildUniqueKey(key);
            if (System.Web.HttpContext.Current != null)
            {
                if (this.IsEnabled)
                    return base.Get(key);
                else
                    return System.Web.HttpContext.Current.Session[key];
            }
            return null;
        }

        /// <summary>
        /// Method removes data from the cache using specified key.
        /// </summary>
        /// <param name="key">Data key.</param>
        public override void Remove(string key)
        {
            key = BuildUniqueKey(key);
            if (System.Web.HttpContext.Current != null)
            {
                if (this.IsEnabled)
                    base.Remove(key);
                else
                    System.Web.HttpContext.Current.Session.Remove(key);
            }
        }

        /// <summary>
        /// Method sets (updates or adds) data into the cache with specified key and expiration.
        /// </summary>
        /// <param name="key">Data key.</param>
        /// <param name="entry">Data to cache.</param>
        public void Set(string key, object entry)
        {
            key = BuildUniqueKey(key);
            DateTime utcExpiry = DateTime.UtcNow.AddMinutes(this.SessionTimeout);
            if (System.Web.HttpContext.Current != null)
            {
                if (this.IsEnabled)
                    base.Set(key, entry, utcExpiry, this.SessionId);
                else
                    System.Web.HttpContext.Current.Session[key] = entry;
            }
        }
    }
}
